#include "comm.h"

int main(int argc, char **argv)
{
    int msqid;
	struct msqid_ds info;
    struct MsgType msg;
    int timeout=0,flag = 0 ;
    int pid ;	
	
	msqid = msgget(IPC_PRIVATE,SVMSG_MODE|IPC_CREAT);
    if(msqid < 0){
        perror("msgget() error");
        return -1 ;
    }	

    pid = fork() ;

    if ( pid == 0 )
    {
		if(atoi(argv[2])==2)
			fork();
		
		if((atoi(argv[2])> 2) &&(atoi(argv[2]) == 4))
		{
			fork();
			fork();
		}
		int i = 0; 
		while(i < atoi(argv[1])) 
		{
			msg.len = i;
			memset(msg.buf, 0, MAXSIZE);
			sprintf(msg.buf, "%d",(int)getpid());
			msg.x = (char)(i + 'a');
			msg.y = (short)(i + 100);

			printf("[CLIENT] pid=%d, msg.len = %d, msg.x = %c, msg.y = %d\n",(int)getpid(), msg.len, msg.x, msg.y);

			/*sending the message      --  mq_send() */
			if(msgsnd(msqid, (char*)&msg, sizeof(struct MsgType), 0) == -1)
			{
				perror("msgsnd() error");
				exit(1);
			}

			i++;
			sleep(1);   
		}
		return 0;
	} else if ( pid > 0) {
		sleep(atoi(argv[1]));
		flag = msgctl( msqid, IPC_STAT, &info) ;
		if ( flag == -1 )
		{
			perror("msgctl() error") ;
			return -1 ;
		}
		while(info.msg_qnum)
		{
			flag = msgctl( msqid, IPC_STAT, &info) ;
			if ( flag == -1 )
			{
				perror("msgctl() error") ;
				return -1 ;
			}

			if(info.msg_qnum != 0)
			{
				timeout = 0;			
				msg.len = -1;
				memset(msg.buf, 0, MAXSIZE);
				msg.x = ' ';
				msg.y = -1;
		 
				/* getting a message */
				if (msgrcv(msqid, (char*)&msg, sizeof(struct MsgType),0,0) == -1) 
				{
					perror("msgrcv() error");
					return -1 ;
				}
				memset(&info, 0, sizeof(struct msqid_ds));
				flag = msgctl( msqid, IPC_STAT, &info) ;
				if ( flag == -1 )
				{
					perror("msgctl() error") ;
					return -1 ;
				}
				//printf("msg_qbytes =%d bytes\n",(int)info.msg_qbytes);
				//printf("msgsnd_pid = %d \n",info.msg_lspid);
				//printf("msgrcv_pid = %d \n",info.msg_lrpid);
				printf("[SERVER] pid=%d, msg.len = %d, msg.x = %c, msg.y = %d msgsnd_pid = %s\n",(int)getpid(), msg.len, msg.x, msg.y, msg.buf);
				sleep(1);
			}
			#if 0
			else
			{
				info.msg_qnum = 1;
				printf("waiting msq %ds\r\n",5 - timeout);
				timeout++;
				sleep(1);
				if(timeout==5)
				{
					printf("waiting msq %ds\r\n",5 - timeout);
					//printf("long time no msg, msgrcv() timeout !\r\n");
					destroy_msq(msqid);
					exit -1;			
				}
			}
			#endif
		}
		destroy_msq(msqid);
	}else{
        perror("fork error");
		destroy_msq(msqid);
    }	
	return 0;
}
